import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  // 设置初始化进入时直接到达登录页面
  {
    path: '/',
    redirect: '/login'
  },
  // 按需导入 需要使用该路由组建时 才带入
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  },
  // 设置home页面的路由
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/views/Home.vue'),
    // 二级路由 子路由的设置
    children: [
      // 当请求home的时候 默认的直接重定向到welcome二级路由
      {
        path: '/home',
        redirect: '/welcome'
      },
      {
        path: '/welcome',
        component: () => import('@/views/Welcome.vue')
      },
      {
        path: '/users',
        component: () => import('@/components/Users/User.vue')
      },
      {
        path: '/roles',
        component: () => import('@/components/Permission/Role.vue')
      },
      {
        path: '/rights',
        component: () => import('@/components/Permission/Permission.vue')
      },
      {
        path: '/params',
        component: () => import('@/components/Goods/Params.vue')
      },
      {
        path: '/goods',
        component: () => import('@/components/Goods/Goods.vue')
      },
      {
        path: '/categories',
        component: () => import('@/components/Goods/Sort.vue')
      },
      {
        path: '/orders',
        component: () => import('@/components/Order/Order.vue')
      },
      {
        path: '/reports',
        component: () => import('@/components/Reports/Reports.vue')
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 添加路由守卫  beforeEach导航守卫
// to  表示将要访问你的路径 form 从哪来  next 是下一个要进行的操作
router.beforeEach((to, from, next) => {
  // 对用户访问的路由进行拦截， 如果访问的是登录页 那么这是就直接放行
  if (to.path === '/login') {
    return next()// 放行
  }
  // 如果访问的不是登录页 则我们需要来检测用户是否登陆 如果登陆 则直接放行  否则 就跳转到登录页
  const token = window.sessionStorage.getItem('token')
  if (!token) { // 没有koken
    return next('/lgoin')
  }
  next()
})

export default router
